/**
 * 操作dom工具
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { $i18n } from '@/locales';
import { colorCalc } from '@/soar/utils/color';
import { toMd5 } from '@/soar';
// import { APP_SPACE } from '@/soar/config';
// 环境名称
const ENV_NAME = import.meta.env.VITE_APP_ENV_NAME || '';
// 项目标题
const TITLE = import.meta.env.VITE_APP_TITLE || '';
// 浏览器代理
const ua = navigator.userAgent;
// 是否微信
const regex1 = /\bMicroMessenger\/([\d\.]+)/;
const regex2 = /ip(hone|od|ad)/i;
// 应用样式
const appStyle: { [k: string]: string } = {};

/**
 * 复制到剪切板
 * @param text
 */
export function copyToClipboard(text: string) {
  // 检查浏览器是否支持 Clipboard API
  if (!navigator.clipboard) {
    // 如果不支持，则使用传统的 document.execCommand("copy") 方式
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    return Promise.resolve();
  }

  // 使用 Clipboard API 复制内容到剪切板
  return navigator.clipboard.writeText(text);
}

/**
 * 添加事件
 * @param el
 * @param event
 * @param listener
 */
export function addEventListener(el: any, event: string, listener: Function) {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      addEventListener(x, event, listener);
    });
  } else {
    el.addEventListener ? el.addEventListener(event, listener) : el.attachEvent(`on${event}`, listener);
  }
}

/**
 * 移除事件
 * @param el
 * @param event
 * @param listener
 */
export function removeEventListener(el: any, event: string, listener: Function) {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      removeEventListener(x, event, listener);
    });
  } else {
    el.removeEventListener ? el.removeEventListener(event, listener) : el.deachEvent(`on${event}`, listener);
  }
}

/**
 * 设置属性
 * @param el
 * @param attr
 * @param value
 */
export function setAttribute(el: any, attr: string, value: any): void {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      x.setAttribute(attr, value);
    });
  } else {
    el.setAttribute(attr, value);
  }
}

/**
 * 移除属性
 * @param el
 * @param attr
 */
export function removeAttribute(el: any, attr: string): void {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      x.removeAttribute(attr);
    });
  } else {
    el.removeAttribute(attr);
  }
}

/**
 * 设置 innerHTML
 * @param el
 * @param html
 */
export function setInnerHtml(el: any, html: string | number) {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      // @ts-ignore
      x.innerHTML = html;
    });
  } else {
    el.innerHTML = html;
  }
}

/**
 * 设置 innerText
 * @param el
 * @param text
 */
export function setInnerText(el: any, text: string | number) {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      // @ts-ignore
      x.innerText = text;
    });
  } else {
    el.innerText = text;
  }
}

/**
 * 添加类
 * @param el
 * @param className
 */
export function addClass(el: any, className: string) {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      x.classList.add(className);
    });
  } else {
    el.classList.add(className);
  }
}

/**
 * 移除类
 * @param el
 * @param className
 */
export function removeClass(el: any, className: string) {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      x.classList.remove(className);
    });
  } else {
    el.classList.remove(className);
  }
}

/**
 * 设置样式
 * @param el
 * @param name
 * @param value
 */
export function setStyle(el: any, name: string, value: string | number) {
  if (typeof el === 'string') {
    document.querySelectorAll(el).forEach((x) => {
      // @ts-ignore
      x.style[name] = value;
    });
  } else {
    el.style[name] = value;
  }
}

/**
 * 触发获取焦点事件
 * @param el
 */
export function focus(el: any) {
  if (el.nodeName === 'INPUT' || el.nodeName === 'TEXTAREA') {
    el.focus?.();
    return true;
  }
  if (el.children?.length) {
    for (const x of el.children) {
      if (focus(x)) {
        return true;
      }
    }
  }
}

/**
 * 更新页面标题
 * @param title
 */
export function updateAppTitle(title: string): void {
  if (title) {
    title = `${$i18n(title)}-${$i18n(TITLE)}`;
  } else {
    title = $i18n(TITLE);
  }
  document.title = `${ENV_NAME}${title}`;
  if (regex1?.test(ua) && regex2?.test(ua)) {
    const i = document.createElement('iframe');
    i.src = '/favicon.ico';
    i.style.display = 'none';
    i.onload = function () {
      setTimeout(function () {
        i.remove();
      }, 9);
    };
    document.body.appendChild(i);
  }
}

/**
 * 更新应用样式
 * @param state
 * @param html
 */
export function updateAppStyle(state: { [k: string]: string }) {
  for (const k in state) {
    appStyle[k] = state[k];
  }
  let cssText = '';
  for (const k in appStyle) {
    cssText += `${k}:${appStyle[k]};`;
  }
  // @ts-ignore
  document.documentElement.style.cssText = cssText;
}

/**
 * 更新主题色
 * @param type
 * @param color1
 * @param color2
 */
export function updateThemeColor(type: string, color1: string, color2: string) {
  const style: any = { [type]: color1 };
  for (let i = 1; i < 10; i += 1) {
    style[`${type}-${i}`] = colorCalc(color1, color2, i / 10);
  }
  updateAppStyle(style);
}

/**
 * 更新应用状态
 * @param state
 */
export function updateAppState(state: any) {
  /*  try {
    const html = document.documentElement;
    html.setAttribute('app-lang', state.lang);
    html.setAttribute('app-platform', state.isMobile ? 'mobile' : 'pc');
    html.setAttribute('app-space', state.space);
    html.setAttribute('app-tabs', state.tabs);
    html.setAttribute('app-color-weak', state.colorWeak);
    html.setAttribute('app-theme-mode', state.dark ? 'dark' : 'light');
    html.className = state.dark ? 'dark' : 'light';
    // 切换主题色
    updateThemeColor('--app-color-primary', state.color || '#409eff', state.dark ? '#141414' : '#ffffff');
    // 更新css变量
    const appStyle: any = { '--space-scale': state.scale };
    for (const key in APP_SPACE) {
      appStyle[`--font-size-${key}`] = APP_SPACE[key]?.fontSize;
    }
    updateAppStyle(appStyle);
  } catch (e) {
    console.error(e);
  } */
}

export function showTooltip(e) {
  const el = e.target;
  let div = document.getElementById('lg-tooltip-box');
  if (!div) {
    div = document.createElement('div');
    div.id = 'lg-tooltip-box';
    div.className = 'lg-tooltip-box';
    div.style.position = 'fixed';
    document.body.append(div);
  }
  if (!el.getAttribute('gl-tooltip-real')) {
    el.addEventListener('mouseout', () => {
      div.style.display = 'none';
      div.innerText = '';
    });
    el.addEventListener('mousemove', (e) => {
      if (e.pageX / window.innerWidth > 0.5) {
        div.style.left = null;
        div.style.right = `${window.innerWidth - e.pageX + 10}px`;
      } else {
        div.style.left = `${e.pageX + 10}px`;
        div.style.right = null;
      }
      if (e.pageY / window.innerHeight > 0.5) {
        div.style.bottom = `${window.innerHeight - e.pageY + 10}px`;
        div.style.top = null;
      } else {
        div.style.bottom = null;
        div.style.top = `${e.pageY + 10}px`;
      }
    });
    el.setAttribute('gl-tooltip-real', '');
  }
  div.style.display = 'block';
  div.innerText = el.title;
}

/**
 * 获取浏览器指纹
 */
function getBrowserFingerprint() {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  context.font = '18pt Arial';
  context.textBaseline = 'top';
  context.fillText('Hello,user.', 2, 2);
  const fingerprint = [
    window.screen.width,
    window.screen.height,
    window.screen.colorDepth,
    window.devicePixelRatio,
    !!window.sessionStorage,
    !!window.localStorage,
    !!window.indexedDB,
    navigator.hardwareConcurrency,
    navigator.userAgent,
    navigator.language,
    navigator.doNotTrack,
    navigator.maxTouchPoints,
    navigator.cookieEnabled,
    new Date().getTimezoneOffset(),
    canvas.toDataURL('image/jpeg').split('base64,')[1],
  ].join('|');
  return toMd5(fingerprint); // 使用信息摘要算法压缩
}
